// formPackage/pages/enterApply/fullNameApply/fullNameApply.js
import { chooseAndUploadQiniuActicon } from "../../../../service/upload_service"
import { sendApplyAgentCodeAction } from "../../../../service/config"
import { queryUserPayInfo } from "../../../../service/user_service"
import debounce from "../../../../tools/debounce"
import { createFullNameEnter, queryFullNameEnterDetail, updateFullNameEnterInfo } from "../../../../service/enter_service"

import {
  CHECK_SUCCESS,
  CHECK_FAIL,
  CHECK_PROGRESS
} from "../../../../service/base_service"

let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    /**
     *  examineStatus:
     * 1:审核中，2:审核成功，3:审核失败
     */
    checkSuccess: CHECK_SUCCESS,
    checkFail: CHECK_FAIL,
    checkProgress: CHECK_PROGRESS,
    themeStyle: "",
    bottomTitle: "提交申请",
    showSuccessPop: false,

    formData: {
      code: "",
      payInfo: {},
      data: {},
    },
    payInfoData: {
      "bankAccount": "",
      "bankName": "",
      "cardBack": "",
      "cardFront": "",
      "openBank": "",
      "openName": "",
    },
    qmData: {
      "areaName": "",
      "areaCode": "",
      "cityCode": "",
      "cityName": "",
      "companyName": "",
      "contactName": "",
      "phone": "",
      "provinceName": "",
      "provinceCode": "",
      "weChat": "",
    },
    showCityArea: false,//所在区域
    singlePopType: "",//单项弹窗类型
    singlePopTitle: "选择",//单项弹窗标题
    showSinglePop: false,//弹出单项弹窗
    isProtocol: false,
    couponCodeBtnStatus: false,
    couponCodeBtnTitle: "获取验证码",
    snsMsgWait: 60,//倒计时
    isEdit: true,//是否可编辑
    examineStatus: 0,//1:审核中，2:审核通过，3:审核失败
    disabled: false,
    isEditPayInfo: true,//是否可编辑这个支付信息
    isCheckOpen:true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      isCheckOpen:app.globalData.isCheckOpen
    })
    this.queryFullNameEnterDetail();
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
    if (app.globalData.selectBankName != "") {
      this.setData({
        'payInfoData.bankName': app.globalData.selectBankName
      })
      app.globalData.selectBankName = "";
    }
  },
  //查询已有的全民入驻信息:
  queryFullNameEnterDetail() {
    wx.showLoading();
    queryFullNameEnterDetail().then(res => {
      wx.hideLoading();
      console.log("JJLog:回填数据是:" + JSON.stringify(res));
      if (res.code == 200) {
        if (res.data.data) {
          this.setData({
            'formData.data': res.data.data,
            'formData.payInfo': res.data.payInfo,
            examineStatus: res.data.data.examineStatus || 0,
            isEdit: res.data.data.isEdit,
            payInfoData: res.data.payInfo || {},
            qmData: res.data.data || {},
          })
          if (res.data.data && res.data.data.contactName) {
            this.setData({
              bottomTitle: "更新申请"
            })
          }
        }
        if (this.data.examineStatus == 1) {
          this.setData({
            disabled: true
          })
        }
        this.setData({
          payInfoData: app.globalData.userPayInfo,
          isEditPayInfo: app.globalData.userPayInfo.isEdit
        })

      }
    }).catch(err => {
      wx.hideLoading();
      console.error("JJLog:回填数据报错:" + JSON.stringify(err));
    })
  },
  //获取这个支付结算信息
  queryUserPayInfo() {
    queryUserPayInfo().then(res => {
      console.log("JJLog:支付信息==:" + JSON.stringify(res));
      if (res.code == 200) {

      }
    }).catch(err => {
      console.error("JJLog:queryUserPayInfo", err);
    })
  },


  //单项输入回调:
  inputCellChange(e) {
    let type = e.detail.key;
    let changeValue = `qmData.${type}`;
    this.setData({
      [changeValue]: e.detail.value
    })
  },
  //银行信息回调
  inputPayChange(e) {
    let type = e.detail.key;
    let changeValue = `payInfoData.${type}`;
    this.setData({
      [changeValue]: e.detail.value
    })
  },
  //手机号输入绑定:
  bindPhoneInputValue(e) {
    this.setData({
      'qmData.phone': e.detail.value
    })
  },
  //验证码输入绑定:
  inputCodeChange(e) {
    this.setData({
      'formData.code': e.detail.value
    })
  },
  //单项选择弹出弹窗:
  singleSelectPop(e) {
    if (this.data.examineStatus == 1) {
      return;
    }
    let type = e.currentTarget.dataset.type;
    if (type == "area") {

      //选择区域
      this.setData({
        showCityArea: true
      })
    } else if (type == "bankName") {
      //选择银行
      // this.setData({
      //   showSinglePop: true,
      //   singlePopType: type,
      //   singlePopTitle: "银行"
      // })
      if (!this.data.isEditPayInfo) {
        return;
      }
      wx.navigateTo({
        url: '/formPackage/pages/selectBankPage/selectBankPage',
      })
    }
    else if (type == "mainType") {
      //主推类型 
      this.setData({
        showSinglePop: true,
        singlePopType: type,
        singlePopTitle: "主推类型"
      })
    }
  },
  //城市区域回调;
  cityPopConfirm(e) {
    let result = e.detail.result;//区县一层的
    this.setData({
      'qmData.areaName': result[2].name,
      'qmData.areaCode': result[2].code,
      'qmData.cityName': result[1].name,
      'qmData.cityCode': result[1].code,
      'qmData.provinceName': result[0].name,
      'qmData.provinceCode': result[0].code,
      showCityArea: false,
    })
  },
  //单项选择回调:
  singlePopSelectCallback(e) {
    let result = e.detail.result;
    let type = e.detail.type;
    if (type == "bankName") {
      this.setData({
        'payInfoData.bankName': result.value,
      })
    }
    this.setData({
      showSinglePop: false
    })
  },
  singlePopHide() {
    this.setData({
      showSinglePop: false
    })
  },
  cityPopHidden() {
    this.setData({
      showCityArea: false
    })
  },
  // 上传图片
  pushImgAction(e) {
    if (this.data.examineStatus == 1) {
      return;
    }
    if (!this.data.isEditPayInfo) {
      return
    }
    let type = e.detail.type;
    chooseAndUploadQiniuActicon('id').then(res => {
      console.log("JJLog:图片上传成功:" + JSON.stringify(res));
      wx.showToast({
        title: '上传成功',
      })
      if (type == "idFront") {
        this.setData({
          'payInfoData.cardFront': res.complateUrl
        })
      } else if (type == "idBack") {
        this.setData({
          'payInfoData.cardBack': res.complateUrl
        })
      }

    }).catch(err => {
      console.log("JJLog:图片上传失败:" + JSON.stringify(err));
      wx.showToast({
        title: '图片上传失败',
        icon: "none"
      })
    })
  },

  /** 发送验证码 */
  clickSendCode() {
    if (this.data.couponCodeBtnStatus) {
      return;
    }
    let that = this;
    //点击了发送按钮，就先禁用掉这个按钮点击
    this.setData({
      couponCodeBtnStatus: true,
    })
    //调用发送验证码接口:
    let phone = this.data.qmData.phone;
    let warn = null;
    if (phone == '') {
      warn = "号码不能为空";
    } else if (phone.trim().length != 11 || !/^1[3|4|5|6|7|8|9]\d{9}$/.test(phone)) {
      warn = "手机号格式不正确";
    } else {
      sendApplyAgentCodeAction(phone).then((data) => {
        //当手机号正确的时候提示用户短信验证码已经发送
        wx.showToast({
          title: '短信验证码已发送',
          icon: 'none',
          duration: 2000
        });
        let inter = setInterval(function () {
          this.setData({
            couponCodeBtnStatus: true,
            couponCodeBtnTitle: this.data.snsMsgWait + 's后重发',
            snsMsgWait: this.data.snsMsgWait - 1
          });
          if (this.data.snsMsgWait < 0) {
            clearInterval(inter)
            this.setData({
              couponCodeBtnTitle: '重新发送',
              snsMsgWait: 60,
              couponCodeBtnStatus: false
            });
          }
        }.bind(this), 1000);

      }).
        catch((err) => {
          that.setData({
            couponCodeBtnStatus: false
          })
          wx.showToast({
            icon: 'none',
            title: err,
          })
        })


    }
    if (warn != null) {
      wx.showModal({
        title: '提示',
        content: warn
      })
      that.setData({
        couponCodeBtnStatus: false
      })
      return;
    }

  },
  //提交信息
  submitInfoAction() {
    let payInfoData = this.data.payInfoData;
    let qmData = this.data.qmData;

    if (!qmData.contactName) {
      wx.showToast({
        title: '请输入联系人',
        icon: "none"
      })
      return;
    }
    if (!qmData.phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: "none"
      })
      return;
    }
    // if (!qmData.weChat) {
    //   wx.showToast({
    //     title: '请输入微信号',
    //     icon: "none"
    //   })
    //   return;
    // }
    if (!this.data.formData.code) {
      wx.showToast({
        title: '请输入验证码',
        icon: "none"
      })
      return;
    }
    if (!qmData.areaName) {
      wx.showToast({
        title: '请选择所在区域',
        icon: "none"
      })
      return;
    }
    // if (!payInfoData.bankName) {
    //   wx.showToast({
    //     title: '请选择银行',
    //     icon: "none"
    //   })
    //   return;
    // }
    // if (!payInfoData.bankAccount) {
    //   wx.showToast({
    //     title: '请输入银行卡号',
    //     icon: "none"
    //   })
    //   return;
    // }
    // if (!payInfoData.openName) {
    //   wx.showToast({
    //     title: '请输入开户名',
    //     icon: "none"
    //   })
    //   return;
    // }
    if (!payInfoData.cardFront) {
      wx.showToast({
        title: '请上传身份证正面照',
        icon: "none"
      })
      return;
    }
    if (!payInfoData.cardBack) {
      wx.showToast({
        title: '请上传身份证反面照',
        icon: "none"
      })
      return;
    }
    if (!this.data.isProtocol) {
      wx.showToast({
        title: '请同意用户政策与隐私协议',
        icon: "none"
      })
      return;
    }

    this.setData({
      'formData.data': qmData,
      'formData.payInfo': payInfoData
    })

    if (this.data.examineStatus != 0) {
      debounce(this.updateApplyData);
    } else {
      debounce(this.submitInfoRequest);
    }
  },

  //提交创建信息
  submitInfoRequest() {
    wx.showLoading();
    console.log("JJLog:提交资料是:" + JSON.stringify(this.data.formData));
    createFullNameEnter(this.data.formData).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        // wx.showToast({
        //   title: "申请已提交，等待审核",
        //   icon: "none"
        // }, 2000)
        // setTimeout(() => {
        //   wx.navigateBack({
        //     delta: 0,
        //   })
        // }, 2000);
        this.setData({
          showSuccessPop: true
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "提交失败",
        icon: "none"
      })
    })
  },

  //更新申请数据;
  updateApplyData() {
    wx.showLoading();
    console.log("JJLog:提交更新资料是:" + JSON.stringify(this.data.formData));
    updateFullNameEnterInfo(this.data.formData).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        // wx.showToast({
        //   title: "申请已提交，等待审核",
        //   icon: "none"
        // }, 2000)
        // setTimeout(() => {
        //   wx.navigateBack({
        //     delta: 0,
        //   })
        // }, 2000);
        this.setData({
          showSuccessPop: true
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "提交失败",
        icon: "none"
      })
    })
  },


  //同意用户协议
  agreeProtocolAction() {
    this.setData({
      isProtocol: !this.data.isProtocol
    })
  },

  //前往用户协议
  pushToProtocol() {

  },
  //
  successPopSure() {
    this.setData({
      showSuccessPop: false,
    })
    wx.switchTab({
      url: '/pages/home/home',
    })
  },




})